<template>
  <div class="template">
    <!-- 上面控制区 -->
    <div class="card topfrom">
      <el-form :model="searchForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入物模型名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select v-model="searchForm.type" placeholder="请选择模型类别">
            <el-option label="属性" value="1"></el-option>
            <el-option label="功能" value="2"></el-option>
            <el-option label="事件" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="init"> 重置 </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="dialogFormVisible = true"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格区 -->
    <div class="card tablebox">
      <el-table
        :data="tableData"
        
        border
        v-loading="tableLoading"
      >
        <el-table-column fixed prop="templateName" label="名称">
        </el-table-column>
        <el-table-column prop="identifier" label="标识符" >
        </el-table-column>
        <el-table-column
          prop="isTop"
          align="center"
          :formatter="formatterTop"
          label="首页显示"
          
        >
        </el-table-column>
        <el-table-column
          prop="isMonitor"
          align="center"
          label="监测值"
          :formatter="formatterMonitor"
         
        >
        </el-table-column>
        <el-table-column
          prop="isSys"
          align="center"
          label="系统定义"
          :formatter="formatterSys"
          
        >
        </el-table-column>
        <el-table-column
          prop="type"
          align="center"
          label="物模型类别"
          :formatter="formatterType"
         
        >
          <template slot-scope="scope">
            <el-tag :type="type(scope.row.type)" disable-transitions>
              {{
                scope.row.type == 1
                  ? "属性"
                  : scope.row.type == 2
                  ? "功能"
                  : "事件"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="datatype"
          align="center"
          label="数据类型"
          :formatter="formatterDataType"
         
        >
        </el-table-column>
        <el-table-column
          prop="specs"
          align="center"
          label="数据定义"
         
        >
          <template slot-scope="scope">
            <div v-html="formatterSpecs(scope.row.specs)"></div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          :formatter="formatterCreateTime"
         
        >
        </el-table-column>
        <el-table-column label="操作" >
          <template v-slot="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="triggerUpdate(row)"
              size="mini"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <el-pagination
      :page-size.sync="pagination.pageSize"
      background
      :total="pagination.total"
      :hide-on-single-page="true"
      :current-page.sync="pagination.pageNum"
      @current-change="init"
      @size-change="init"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <!-- 新增/修改 -->
    <el-dialog
      :title="+bigFrom.templateId === 0 ? '添加通用物模型' : '修改通用物模型'"
      :visible.sync="dialogFormVisible"
      :before-close="closeDialog"
    >
      <el-form
        :model="bigFrom"
        ref="bigFrom"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- :rules="rules" -->
        <el-form-item label="模型名称" prop="name">
          <el-input
            v-model="bigFrom.templateName"
            placeholder="请输入物模型名称，例如：温度"
          ></el-input>
        </el-form-item>
        <el-form-item label="标识符" prop="name">
          <el-input
            v-model="bigFrom.identifier"
            placeholder="请输入标识符，例如：temperature"
          ></el-input>
        </el-form-item>
        <el-form-item label="模型名称">
          <el-radio-group v-model="bigFrom.type" size="small">
            <el-radio-button label="1">属性</el-radio-button>
            <el-radio-button label="2">功能</el-radio-button>
            <el-radio-button label="3">事件</el-radio-button>
          </el-radio-group>
          <div style="margin: 20px"></div>
        </el-form-item>
        <el-form-item
          label="首页展示"
          v-show="bigFrom.type == 1 || bigFrom.type == 2"
          prop="isTop"
        >
          <el-switch
            v-model="bigFrom.isTop"
            active-color="#13ce66"
            inactive-color="#ddd"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          label="实时监测"
          v-show="bigFrom.type == 1"
          prop="isMonitor"
        >
          <el-switch
            v-model="bigFrom.isMonitor"
            active-color="#13ce66"
            inactive-color="#ddd"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="数据类型" prop="region">
          <el-select v-model="bigFrom.datatype" placeholder="请选择数据类型">
            <el-option label="整数" value="integer"></el-option>
            <el-option label="小数" value="decimal"></el-option>
            <el-option label="布尔" value="bool"></el-option>
            <el-option label="枚举" value="enum"></el-option>
            <el-option label="字符串" value="string"></el-option>
            <el-option label="数组" value="array"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取值范围">
          <el-input-number
            v-model="bigFrom.specs.min"
            controls-position="right"
            placeholder="最小值"
          ></el-input-number>
          &nbsp;&nbsp;&nbsp;&nbsp; 到
          <el-input-number
            v-model="bigFrom.specs.max"
            controls-position="right"
            placeholder="最大值"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="单位">
          <el-input
            v-model="bigFrom.specs.unit"
            placeholder="请输入单位，例如℃"
          ></el-input>
        </el-form-item>
        <el-form-item label="步长">
          <el-input
            v-model="bigFrom.specs.step"
            placeholder="请输入步长，例如1"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="small"
          :loading="confirmLoading"
          @click="submit"
        >
          确 定
        </el-button>
        <el-button @click="closeDialog" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Template",
  data() {
    return {
      searchForm: {
        name: "",
        type: "",
      },
      tableLoading: false,
      tableData: [
        // {
        //   templateName: "name", //名称
        //   identifier: "type", //标识符
        //   isTop: 0, //首页显示  0：否  1：是
        //   isMonitor: 0, //监测值 0：否 1：是
        //   isSys: 0, //系统定义  0：否 1：是
        //   type: 2, //物模型类别 1：属性  2：功能  3：事件
        //   datatype: "integer", //数据类型 integer:整数 decimal：小数 bool：布尔 enum：枚举 string：字符串 array：数组
        //   specs:
        //     '{"max": 4, "min": -6, "step": 6, "type": "integer", "unit": "-4"}', //数据定义
        //   createTime: "2022-10-01 10:10:56", //创建时间
        // },
      ],
      pagination: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },

      // dialog
      confirmLoading: false,
      dialogFormVisible: false,
      ruleForm: {},
      labelPosition: "1",
      bigFrom: {
        templateId: 0, //0新增  否则修改
        templateName: "", //物模型名称
        identifier: "", //标识符
        isTop: false, //首页展示
        isMonitor: false, //实时监测
        datatype: "integer", //数据类型
        specs: {
          max: "",
          min: "",
          step: "",
          type: "",
          unit: "",
        },
        //   '{"max": 4, "min": -6, "step": 6, "type": "integer", "unit": "-4"}',
        // 更新需要从服务器获取的数据
        createBy: null,
        createTime: "",
        delFlag: null,
        isSys: "",
        params: {},
        remark: null,
        searchValue: null,
        tenantId: 1,
        tenantName: "wumei",
        type: 1,
        updateBy: "wumei",
        updateTime: null,
        // 新增需要的数据
        userId: null,
        userName: null,
      },
    };
  },
  methods: {
    // 表格相关
    // 表格物模型样式
    type(type) {
      if (type === 1) {
        return "primary";
      } else if (type === 2) {
        return "success";
      } else {
        return "warning";
      }
    },

    // 格式化
    formatterTop(row) {
      return row.isTop === 0 ? "否" : "是";
    },
    formatterMonitor(row) {
      return row.isMonitor === 0 ? "否" : "是";
    },
    formatterSys(row) {
      return row.isSys === 0 ? "否" : "是";
    },
    // formatterType(row) {
    //   if (row.type === 1) {
    //     return "属性";
    //   } else if (row.type === 2) {
    //     return "功能";
    //   } else {
    //     return "事件";
    //   }
    // },
    formatterDataType(row) {
      if (row.datatype === "integer") return "整数";
      else if (row.datatype === "decimal") return "小数";
      else if (row.datatype === "bool") return "布尔";
      else if (row.datatype === "enum") return "枚举";
      else if (row.datatype === "string") return "字符串";
      else {
        return "数组";
      }
    },
    formatterSpecs(json) {
      //转化 JSON字符串
      // console.log(json);
      let specs = JSON.parse(json);
      // console.log(specs);
      if (specs.type === "integer" || specs.type === "decimal") {
        return (
          "<span style='display:inline-block;'>最大值：<span style=\"color:#F56C6C\">" +
          specs.max +
          '</span></span>最小值：<span style="color:#F56C6C">' +
          specs.min +
          "</span><br /><span style='display:inline-block;'>步长：<span style=\"color:#F56C6C\">" +
          specs.step +
          '</span></span>单位：<span style="color:#F56C6C">' +
          specs.unit
        );
      } else if (specs.type === "string") {
        return (
          '最大长度：<span style="color:#F56C6C">' + specs.maxLength + "</span>"
        );
      } else if (specs.type === "array") {
        return (
          '数组类型：<span style="color:#F56C6C">' + specs.arrayType + "</span>"
        );
      } else if (specs.type === "enum") {
        let items = "";
        for (let i = 0; i < specs.enumList.length; i++) {
          items =
            items +
            "<span style='width:50%;display:inline-block;'>" +
            specs.enumList[i].value +
            "：<span style='color:#F56C6C'>" +
            specs.enumList[i].text +
            "</span></span>";
          if (i > 0 && i % 2 != 0) {
            items = items + "<br />";
          }
        }
        return items;
      } else if (specs.type === "bool") {
        return (
          "<span style='width:50%;display:inline-block;'>0：<span style=\"color:#F56C6C\">" +
          specs.falseText +
          '</span></span>1：<span style="color:#F56C6C">' +
          specs.trueText
        );
      }
    },
    formatterCreateTime(row) {
      return row.createTime.split(" ")[0];
    },
    // 搜索
    search() {
      let templateName = this.searchForm.name,
        type = this.searchForm.type;
      this.init(_, templateName, type);
    },
    // 根据当前页获取数据
    async init(_, templateName, type) {
      this.tableLoading = true;
      try {
        let { pageSize, pageNum } = this.pagination;
        let { code, rows, total } = await this.$api.template.getList(
          pageNum,
          pageSize,
          _,
          templateName,
          type
        );
        if (+code === 200) {
          this.tableData = rows;
          this.pagination.total = +total;
        }
      } catch (_) {
        _;
      }
      this.tableLoading = false;
    },
    // 关闭dialog && 清空表单信息
    closeDialog() {
      this.dialogFormVisible = false;
      this.confirmLoading = false;
      // this.$refs.formIns.resetFields();
      // this.ruleForm.carouselId = 0; //上述操作不会清空id(id并不是表单项)需要手动设置
      this.bigFrom = {
        templateId: 0, //0新增  否则修改
        templateName: "", //物模型名称
        identifier: "", //标识符
        isTop: false, //首页展示
        isMonitor: false, //实时监测
        datatype: "decimal", //数据类型
        specs: {
          max: "",
          min: "",
          step: "",
          unit: "",
        },
        //   '{"max": 4, "min": -6, "step": 6, "type": "integer", "unit": "-4"}',
      };
    },
    // 触发修改按钮
    triggerUpdate(row) {
      let {
        templateId,
        templateName,
        identifier,
        isTop,
        isMonitor,
        datatype,
        specs,
        type,
      } = row;
      // 先把修改项的id存储到表单状态中
      this.bigFrom.templateId = templateId;
      // 把信息填到各个表单中(row中包含表单需要的数据,直接赋值即可)
      this.bigFrom.templateName = templateName;
      this.bigFrom.identifier = identifier;
      this.bigFrom.isTop = isTop === 0 ? false : true;
      this.bigFrom.isMonitor = isMonitor === 0 ? false : true;
      this.bigFrom.datatype = datatype;
      this.bigFrom.templateName = templateName;
      specs = JSON.parse(specs);
      this.bigFrom.specs.max = specs.max;
      this.bigFrom.specs.min = specs.min;
      this.bigFrom.specs.step = specs.step;
      this.bigFrom.specs.unit = specs.unit;
      this.bigFrom.specs.type = datatype;

      // this.bigFrom.type = type;
      // console.log(this.bigFrom.type);
      this.dialogFormVisible = true;
    },
    // 新增 && 修改信息
    async submit() {
      try {
        this.confirmLoading = true;
        let {
          templateId,
          createBy,
          createTime,
          datatype,
          delFlag,
          identifier,
          isMonitor,
          isSys,
          isTop,
          remark,
          specs,
          templateName,
          tenantId,
          tenantName,
          type,
          updateBy,
          updateTime,
          userId,
          userName,
          params,
          searchValue,
        } = this.bigFrom;
        let funcAPI = this.$api.template.insertInfo;
        specs = JSON.stringify(specs);
        isMonitor = isMonitor === false ? 0 : 1;
        isTop = isTop === false ? 0 : 1;
        isSys = isSys === false ? 0 : 1;
        let data = {
          createBy,
          createTime,
          datatype,
          delFlag,
          identifier,
          isMonitor,
          isSys,
          isTop,
          remark,
          specs,
          templateId,
          templateName,
          tenantId,
          tenantName,
          type,
          updateBy,
          updateTime,
          userId,
          userName,
        };
        if (+templateId !== 0) {
          //修改
          funcAPI = this.$api.template.updateInfo;
          data = {
            createBy,
            createTime,
            datatype,
            delFlag,
            identifier,
            isMonitor,
            isSys,
            isTop,
            params,
            remark,
            searchValue,
            specs,
            templateId,
            templateName,
            tenantId,
            tenantName,
            type,
            updateBy,
            updateTime,
          };
          data.templateId = templateId;
        }
        let { code } = await funcAPI(data);
        if (+code === 200) {
          this.$message.success("恭喜您，操作成功");
          this.closeDialog();
          this.init();
        } else {
          this.$message.error("操作失败，请稍后再试");
        }
      } catch (_) {}
    },
  },

  async created() {
    await this.$api.template.thingsType();
    await this.$api.template.dataType();
    await this.$api.template.iotYesNo();
    this.init();
  },
};
</script>

<style lang="less" scoped>
.template {
  margin-left: 10px;
  background: #fff;
  border-radius: 20px;
  .card {
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    background-color: #fff;
    overflow: hidden;
    color: #303133;
    transition: 0.3s;
    padding: 15px 20px 20px 20px;
  }
  .topfrom {
    margin-bottom: 5px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .el-form {
      position: relative;
      .el-form-item__content {
        line-height: 23px;
      }
      .el-form-item {
        height: 36px;
        overflow: hidden;
        display: inline-block;
        margin-bottom: 0px;
        /deep/.el-input__inner {
          height: 30px;
        }
        /deep/ .el-button {
          height: 30px;
          font-size: 12px !important;
          line-height: 1px !important;
        }
      }
      .el-form-item:nth-child(3) {
        position: absolute;
        right: 180px;
      }
      .el-form-item:last-child {
        position: absolute;
        right: 20px;
      }
    }
  }
  .tablebox {
    border-bottom: none;
    .el-table__row {
      .el-button {
        height: 30px;
        font-size: 12px;
        line-height: 10px;
      }
    }
  }
  .el-pagination {
    padding-bottom: 50px;
    padding-left: 300px;
  }
  // .small-ruleForm {
  //   .el-form-item {
  //     margin-bottom: 20px;
  //   }
  // }
  /deep/.el-dialog {
    width: 550px;
    .el-form {
      .el-form-item:nth-child(3) {
        border-bottom: 1px solid #ddd;
        width: 90%;
        margin-left: 20px;
      }
    }
  }
}
</style>